package com.climber.spb_rabbitmq.spb_backqueue.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author frx
 * @version 1.0
 * @date 2022/7/25  22:31
 * desc:
 * 更加健全的发布确认模式
 */
@Configuration
public class RabbitMQConfig {
    public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";
    public static final String CONFIRM_QUEUE_NAME = "confirm.queue";
    public static final String CONFIRM_ROUTINGKEY = "CRK";

    //备用交换机
    public static final String BACKUP_EXCHANGE = "back.exchange";
    //备份队列
    public static final String BACK_QUEUE = "back.queue";
    //警告队列
    public static final String WARN_QUEUE = "warn.queue";

    //    @Bean("confirmExchange")
//    public DirectExchange confirmExchange() {
//        return new DirectExchange(CONFIRM_EXCHANGE_NAME, false, false);
//    }
    @Bean("confirmExchange")
    public DirectExchange confirmExchange() {
        ExchangeBuilder
                exchangeBuilder =
                ExchangeBuilder.directExchange(CONFIRM_EXCHANGE_NAME).durable(false)
                        //设置该交换机的备份交换机
                        .withArgument("alternate-exchange", BACKUP_EXCHANGE);
        return exchangeBuilder.build();
    }


    // 声明确认队列
    @Bean("confirmQueue")
    public Queue confirmQueue() {
        return QueueBuilder.nonDurable(CONFIRM_QUEUE_NAME).build();
    }

    // 声明确认队列绑定关系
    @Bean
    public Binding queueBinding(@Qualifier("confirmQueue") Queue queue,
                                @Qualifier("confirmExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(CONFIRM_ROUTINGKEY);
    }


    //备份交换机
    @Bean
    public Queue backqueue() {
        return new Queue(BACK_QUEUE, false);
    }

    @Bean
    public Queue warnqueue() {
        return new Queue(WARN_QUEUE, false);
    }

    @Bean
    public FanoutExchange backexchange() {
        return new FanoutExchange(BACKUP_EXCHANGE, false, false);
    }

    @Bean
    public Binding backupbinding() {
        return BindingBuilder.bind(backqueue()).to(backexchange());
    }

    @Bean
    public Binding warnbinding() {
        return BindingBuilder.bind(warnqueue()).to(backexchange());
    }
}


